package cn.edu.swu.safety;

import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class AuthFilter extends HttpFilter {

    public final static String AUTH_STATUS="AUTH_STATUS";
    public final static String INIT_PARAM_IGNORE="ignoreUrls";

    private String[] ignoreUrls=null;

    public void init(FilterConfig filterConfig){
        String urls=filterConfig.getInitParameter(INIT_PARAM_IGNORE);
        if(urls!=null){
            this.ignoreUrls=urls.split(";");
        }
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String requestURI = request.getRequestURI();
        for (String ignoreurl:this.ignoreUrls) {
            if(requestURI.endsWith(ignoreurl)){
                chain.doFilter(request,response);
                return;
            }
        }

        HttpSession session = request.getSession(true);
        AuthStatus authStatus=(AuthStatus)session.getAttribute(AUTH_STATUS);

        if(authStatus!=null&&authStatus.equals(AuthStatus.LOGIN_SUCCESS)) {
            chain.doFilter(request, response);
        }else{
              response.sendRedirect("./index.html");
        }
    }
}
